package com.just.company_server.service.impl;

import com.just.company_server.dao.CompanyMapper;
import com.just.company_server.model.Company;
import com.just.company_server.model.CompanyExample;
import com.just.company_server.service.CompanyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : baibaiwucahng
 * @date : 2020/3/8  23:27
 */
@Service
public class CompanyServiceImpl implements CompanyService {

    @Resource
    private CompanyMapper companyMapper;
    /**
     *  分页获取所有列表
     */
    @Override
    public List<Company> getAllCompany() {
        List<Company> companies = companyMapper.selectByExample(new CompanyExample());
        return companies;
    }

    @Override
    public Company getCompanyById(Integer id) {
        CompanyExample example = new CompanyExample();
        example.createCriteria().andIdEqualTo(id);
        List<Company> companies =  companyMapper.selectByExample(example);
        if (companies.size() != 1) {
            // 抛出异常
        }
        return companies.get(0);
    }

    /**
     *  插入公司
     * @param company
     * @return
     */
    @Override
    public void insertCompany(Company company) {
        // 判断公司是否存在
        if (isExistCompany(company.getName())) {
            // 抛出异常
        }
        companyMapper.insert(company);
    }

    /**
     * 编辑公司
     * @param company
     */
    @Override
    public void editCompany(Company company) {
        companyMapper.updateByPrimaryKey(company);

    }

    /**
     * 删除公司
     * @param id
     */
    @Override
    public void deleteCompanyById(Integer id) {
        companyMapper.deleteByPrimaryKey(id);
    }

    /**
     * 判断公司是否存在
     * @param name
     * @return
     */
    public boolean isExistCompany(String name) {
        CompanyExample example = new CompanyExample();
        example.createCriteria().andNameEqualTo(name);
        List<Company> companies =  companyMapper.selectByExample(example);
        return companies.size() > 0;
    }
}
